package com.pets.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@RestController
@RequestMapping("/upload")
@Api(tags = "文件与图片上传接口")
public class UploadController {

    @ApiOperation("图片上传接口")
    @PostMapping("/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "请选择要上传的文件";
        }
        String baseLocation = "D:\\aliyun_workspace\\java_food\\server\\upload";
        String uploadLocation = baseLocation + "\\tmp";
        // 创建上传目录（如果目录不存在）
        File uploadDir = new File(uploadLocation);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        try {
            // 生成新的文件名
            String originalFileName = StringUtils.cleanPath(file.getOriginalFilename());
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String randomString = UUID.randomUUID().toString().replace("-", "");
            String fileName = randomString + "_" + timeStamp + fileExtension;
            String filePath = uploadLocation + File.separator + fileName;
            // 保存文件
            File dest = new File(filePath);
            file.transferTo(dest);
            // 返回上传成功的图片访问路径
            String imageUrl = "http://localhost:1305/staticfiles/tmp/" + fileName;
            return imageUrl;
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败：" + e.getMessage();
        }
    }
}
